package com.lht.testDemo;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author Eric
 * @version 1.0
 * @date 2019-11-26
 */
public class StringBuilderTest {

    @Test
    public void testClear() {

        StringBuilder sb = new StringBuilder();
        sb.append("hello world");

        // 3
        sb = new StringBuilder();

        // 博客说 这种最优 1
        sb.delete(0, sb.length());

        // 2
        sb.setLength(0);
    }

    /**
     * @param
     * @return void
     * @throws
     * @author Eric
     * @date 2020/1/6
     **/
    @Test
    public void testInsertPerformance() {

        List<Integer> list = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 10000; i++) {
            list.add(random.nextInt(10000));
        }

        StringBuilder sb = new StringBuilder();
        long start = System.nanoTime();
        list.forEach(v -> {
            sb.insert(0, v);
        });
        long end = System.nanoTime();
        long count = end - start;
        System.out.println("insert耗时 =>" + count);

        String a = "";
        start = System.nanoTime();
        for (Integer i : list) {
            a = i + a;
        }
        end = System.nanoTime();
        count = end - start;
        System.out.println("+ 耗时 =>" + count);
    }


}
